package algorithm.leetcode.simple;

/*
 计算给定二叉树的所有左叶子之和。
 */

/**
 * @author jack.wu
 * @version 1.0
 * @date 2020/10/27
 */
public class Question404 {

    public static void main(String[] args) {

    }

    public int sumOfLeftLeaves(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int sum = 0;
        if (root.left != null) {
            // 左子树如果是叶子节点累加 如果不是则继续向下找
            sum += isLeafNode(root.left) ? root.left.val : sumOfLeftLeaves(root.left);
        }
        if (root.right != null && !isLeafNode(root.right)) {
            // 如果右子树不为空同时右子树还不是叶子节点 继续向下找
            sum += sumOfLeftLeaves(root.right);
        }
        return sum;
    }

    private boolean isLeafNode(TreeNode node) {
        return node.left == null && node.right == null;
    }



    private static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }
}
